//
//  DHHomeController.m
//  精品酒店
//
//  Created by DIANGHONG on 2018/5/7.
//  Copyright © 2018年 DIANGHONG. All rights reserved.
//

#import "DHHomeController.h"
#import <WebKit/WebKit.h>
#import "DHAdvCell.h"
#import "DHNavCell.h"
#import "DHNormalCell.h"
#import <CoreLocation/CoreLocation.h>

NSString *NavCellID = @"NavCellID";
NSString *AdvCellID = @"AdvCellID";
NSString *normalCellID = @"normalCellID";
@interface DHHomeController () <DHNormalCellDelegate, CLLocationManagerDelegate>

@property(nonatomic ,assign)int page;


@property(nonatomic ,strong)DHHomeViewModel *viewModel; // 视图模型

@property(nonatomic ,strong)UIButton *leftNavButton; // 导航左边按钮

@property(nonatomic ,strong)DHRightNavButton *rightNavButton; // 导航右边按钮

@property(nonatomic ,strong)NSArray *menuItems;  // 右 导航栏菜单item数组

@property (nonatomic,strong ) CLLocationManager *locationManager;//定位服务
@property (nonatomic,copy) NSString *currentCity;   //城市
@property (nonatomic,copy) NSString *strLatitude;   //经度
@property (nonatomic,copy) NSString *strLongitude;  //维度

@end

@implementation DHHomeController

- (NSArray *)menuItems{
    if(_menuItems)
    {
        return _menuItems;
    }
    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:5];
    [self.viewModel.homeDatas.notice enumerateObjectsUsingBlock:^(DHNoticeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
     {
         YCXMenuItem *item = [YCXMenuItem menuItem:obj.title image:nil tag:idx userInfo:@{@"urlStr":obj.url}];
         item.titleFont = [UIFont systemFontOfSize:8];
         [arrayM addObject:item];
     }];

    return arrayM.copy;
}
- (void)locatemap{
    
    if ([CLLocationManager locationServicesEnabled]) {
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestAlwaysAuthorization];
        _currentCity = [[NSString alloc]init];
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 5.0;
        [_locationManager startUpdatingLocation];
    }
}


#pragma mark: - navitem左边按钮懒加载
- (UIButton *)leftNavButton{
    if (!_leftNavButton) {
        _leftNavButton = [[UIButton alloc]init];
        UIImage *image = [UIImage createNewImage:[UIImage imageNamed:@"定位 (1)"] newSize:CGSizeMake(22, 22)];
        [_leftNavButton setImage:image forState:UIControlStateNormal];
        [_leftNavButton setTitle:@"未知位置" forState:UIControlStateNormal];
        _leftNavButton.titleLabel.font = [UIFont systemFontOfSize:13];
    }
    return _leftNavButton;
}

- (DHRightNavButton *)rightNavButton{
    if (!_rightNavButton) {
        _rightNavButton = [DHRightNavButton buttonWithTitle:@"业务通告" frame:CGRectMake(0, 0, 100.5, 44)];
        [_rightNavButton addTarget:self action:@selector(rightNavButtonCilck:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightNavButton;
}
- (DHHomeViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[DHHomeViewModel alloc] init];
    }
    return _viewModel;
}
#pragma mark - 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication]openURL:settingURL];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    [_locationManager stopUpdatingLocation];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //当前的经纬度
    NSLog(@"当前的经纬度 %f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    
    self.strLongitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude];
    self.strLatitude =  [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude];;
    //这里的代码是为了判断didUpdateLocations调用了几次 有可能会出现多次调用 为了避免不必要的麻烦 在这里加个if判断 如果大于1.0就return
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //地理反编码 可以根据坐标(经纬度)确定位置信息(街道 门牌等)
        [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count >0) {
                CLPlacemark *placeMark = placemarks[0];
                self->_currentCity = placeMark.locality;
                if (!self->_currentCity) {
                    self->_currentCity = @"无法定位当前城市";
                }
                //看需求定义一个全局变量来接收赋值
                //            NSLog(@"当前国家 - %@",placeMark.country);//当前国家
                NSLog(@"当前城市 - %@",self->_currentCity);//当前城市
                [self.leftNavButton setTitle: self->_currentCity forState:UIControlStateNormal];
                //[self.addrBtn setTitle:self->_currentCity forState:UIControlStateNormal];
                //            NSLog(@"当前位置 - %@",placeMark.subLocality);//当前位置
                //            NSLog(@"当前街道 - %@",placeMark.thoroughfare);//当前街道
                //            NSLog(@"具体地址 - %@",placeMark.name);//具体地址
                NSString *message = [NSString stringWithFormat:@"%@,%@,%@,%@,%@",placeMark.country,self->_currentCity,placeMark.subLocality,placeMark.thoroughfare,placeMark.name];
                
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"好", nil];
                //            [alert show];
            }else if (error == nil && placemarks.count){
                
                NSLog(@"NO location and error return");
            }else if (error){
                
                NSLog(@"loction error:%@",error);
            }
        }];
    });
    [self loadHomeTaskListWithPullUP:NO];
}



//- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
//{
//     DHBaseController *vc = viewController.childViewControllers.firstObject;
//    if ([vc isMemberOfClass:[DHServiceController class]]) {
//        // 判断手机是否安装QQ
//        NSURL *url = [NSURL URLWithString:@"mqq://"];
//        if([[UIApplication sharedApplication] canOpenURL:url]){
//            [[UIApplication sharedApplication] openURL:url];
//
//        } else {
//            UIAlertView*ale=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您没有安装手机QQ，请安装手机QQ后重试，或用PC进行操作。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//            ale.delegate = self;
//            [ale show];
//
//        }
//        return NO;
//    }
//    return YES;
//}

#pragma mark: - UITabBarControllerDelegate
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    DHBaseController *vc = viewController.childViewControllers.firstObject;
    
    if ([vc isMemberOfClass:[DHOrderController class]] ||
        [vc isMemberOfClass:[DHMineViewController class]]) {
        
        
        if (![DHNetworkManager.shareManager userAccount].key) {
            DHLoginController *loginVC = [[DHLoginController alloc] init];
            
            [self.navigationController pushViewController:loginVC animated:true];
            return NO;
        }
        return YES;
        
    }
    if ([vc isMemberOfClass:[DHServiceController class]]) {
        // 判断手机是否安装QQ
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",self.viewModel.homeDatas.qq]];
        if([[UIApplication sharedApplication] canOpenURL:url]){
            [[UIApplication sharedApplication] openURL:url];
            
        } else {
            UIAlertView*ale=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您没有安装手机QQ，请安装手机QQ后重试，或用PC进行操作。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            ale.delegate = self;
            [ale show];
            
        }
        return NO;
    }
    // NSLog(@"%@---%@",viewController.childViewControllers.firstObject,[self class]);
    
    return YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
   
    [self setupNav];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //[DHNetworkManager.shareManager requestHomeDatas];
    [self.rightNavButton bringSubviewToFront:self.tableView];
    
    [self loadHomeDataInfo];
    
    self.tabBarItem.title = @"首页";

    [self setupNav];
    
    [self locatemap];
     self.page = 1;
    //self.tabBarController.selectedIndex = 0;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadHomeTaskListWithPullUP:YES];
    }];
    
//    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(showLoginVC) name:kShouldLoginNotification object:nil];
}
//- (void)showLoginVC{
//
//}

#pragma mark: - 加载首页数据
- (void)loadHomeTaskListWithPullUP:(BOOL)pullup
{
    
    [self.viewModel loadHomeStatusListWithWithPullUP:pullup page:self.page lng:self.strLongitude lat:self.strLatitude area_name:@"深圳市" FiniedBlock:^(BOOL hasMore, BOOL isSuccess) {
        if (!isSuccess) {
            [self.tableView.mj_footer endRefreshing];
            return ;
        }
        [self.tableView reloadData];
        

    }];
}


#pragma mark: - 导航栏右边按钮监听
- (void)rightNavButtonCilck:(DHRightNavButton *)sender
{
    if (!(self.viewModel.homeDatas.notice.count > 0)) {
        return;
    }
    [YCXMenu isShow] ? [YCXMenu dismissMenu] : [self showMenuWithButton:sender];
}

#pragma mark: - 导航右边菜单点击事件监听
- (void)showMenuWithButton:(DHRightNavButton *)button
{
    
    [YCXMenu showMenuInView:self.view
                    fromRect:CGRectMake(self.view.bounds.size.width - 50,
                    CGRectGetMaxY(self.navigationController.navigationBar.frame) - 20
                    , 30
                    , button.bounds.size.height)
                    menuItems:self.menuItems
                    selected:^(NSInteger index, YCXMenuItem *item) {
                        DHWebViewController *webVC = [[DHWebViewController alloc] init];
                        webVC.urlStr = item.userInfo[@"urlStr"];
                        webVC.hidesBottomBarWhenPushed = YES;
                        [self.navigationController pushViewController:webVC animated:true];
                                       
                    }];
}

#pragma mark: - 设置导航栏
- (void)setupNav
{
   
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:211.0f/255.0f
                                                                             green:60.0f/255.0f
                                                                              blue:50.0f/255.0f alpha:1]];
    self.navigationController.title = @"";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.leftNavButton];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightNavButton];
    [self.navigationItem.rightBarButtonItem setWidth:100];
    //  [self.navigationItem.leftBarButtonItem setWidth:100];
    
    self.navigationController.navigationBar.hidden = false;
    self.tabBarController.tabBar.hidden = false;
    
}

#pragma mark: - 设置界面
- (void)setupUI{
    [super setupUI];
    
    //self.title = @"首页";
    [self.tableView setBackgroundColor:UIColor.whiteColor];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView registerClass:[DHAdvCell class] forCellReuseIdentifier:AdvCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHNavCell" bundle:nil] forCellReuseIdentifier:NavCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"DHNormalCell" bundle:nil] forCellReuseIdentifier:normalCellID];
}


#pragma mark: - 加载数据
- (void)loadHomeDataInfo{
    
    [self.viewModel loadHomeDataWithFiniedBlock:^(BOOL isSuccess) {
        
        if (!isSuccess) {
            return ;
        }
//        [NSNotificationCenter.defaultCenter postNotificationName:kSuccessGetQQNotification object:nil userInfo:@{@"qq":self.viewModel.homeDatas.qq}];
        
        [self.tableView reloadData];
    }];
}

#pragma mark: - TableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger numRow = (section != 2) ? 1 : self.viewModel.taskList.count;
    
    return numRow;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self getReuseCellIDWithSection:indexPath.section]
                                                            forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [self sendPorpertyForCell:cell idx:indexPath];
    
    
    return cell;
}

#pragma mark: - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [self.viewModel calcRowHeightWithSection:indexPath.section];
}

#pragma mark: - 查看详情按钮监听
- (void)normalCell:(DHNormalCell *)cell detailButtonClickWithModel:(DHOrderModel *)model
{
    DHOrderDetailController *detailVC = [[DHOrderDetailController alloc] init];
    detailVC.hidesBottomBarWhenPushed = true;
    
    NSMutableDictionary *requestInfo = [NSMutableDictionary dictionary];
    requestInfo[@"id"] = model.ID;
    requestInfo[@"lng"] = self.strLongitude;
    requestInfo[@"lat"] = self.strLatitude;
    requestInfo[@"key"] = DHNetworkManager.shareManager.userAccount.key;
    requestInfo[@"store_id"] = model.store_id;

    detailVC.requestInfo = requestInfo.copy;
    
    [self.navigationController pushViewController:detailVC animated:true];
}
#pragma mark: - 立即预约按钮监听
- (void)normalCell:(DHNormalCell *)cell preOrderButtonClickWithModel:(NSString *)model
{
    if (DHNetworkManager.shareManager.userAccount.is_auth.boolValue)
    {
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"key"] = DHNetworkManager.shareManager.userAccount.key;
        param[@"id"] = cell.model.ID;
        param[@"store_id"] = cell.model.store_id;
        
        [DHNetworkManager.shareManager postTaskWithParam:param completion:^(BOOL isSuccess, NSString *statusInfo)
        {
            if (!isSuccess) {
                [SVProgressHUD showErrorWithStatus:statusInfo];
                return ;
            }
            [SVProgressHUD showSuccessWithStatus:statusInfo];
        }];
    }else{
        //NSDictionary *params = @{@"key":DHNetworkManager.shareManager.userAccount.key};
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"key"] = DHNetworkManager.shareManager.userAccount.key;
        if (!params[@"key"])
        {
            [SVProgressHUD showErrorWithStatus:@"请先登录"];
            return;
        }
        DHTipsView *tipView = [DHTipsView tipViewWithFrame:CGRectMake(0, 0, kScreenWidth - 24, 110)];
        STModal *modal = [STModal modal];
        modal.hideWhenTouchOutside = true;
        [modal showContentView:tipView animated:YES];
        
        tipView.completUserInfoClick =
        ^{
            [modal hide:true];
            UIStoryboard * story = [UIStoryboard storyboardWithName:@"DHUserInfoController" bundle:nil];
            
            DHUserInfoController *userInfoVC = [story instantiateViewControllerWithIdentifier:@"userInfo"];
            userInfoVC.params = params;
            userInfoVC.hidesBottomBarWhenPushed = true;
            [self.navigationController pushViewController:userInfoVC animated:true];
        };
    }
}

#pragma mark: - 给cell设置数据
- (void)sendPorpertyForCell:(UITableViewCell *)cell idx:(NSIndexPath *)idx{
    
    switch (idx.section) {
        case 0:
        {
            [(DHAdvCell *)cell setBanners:self.viewModel.homeDatas.banner];
            [(DHAdvCell *)cell setAdvCellClickBlock:^(NSString *urlStr) {
                
                DHWebViewController *webVC = [[DHWebViewController alloc] init];
                webVC.urlStr = urlStr;
                webVC.title = @"精品酒店网";
                webVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:webVC animated:true];
            }];
        }
            break;
        case 1:
            [(DHNavCell *)cell setListsModel:self.viewModel.homeDatas.list];
            break;
        default:
            [(DHNormalCell *)cell setModel:self.viewModel.taskList[idx.row]];
            [(DHNormalCell *)cell setDelegate:self];
            break;
    }
    
}


/**
 根据section返回可重用cellID

 @param section section
 @return cellID
 */
- (NSString *)getReuseCellIDWithSection:(NSInteger)section{
    
    switch (section) {
        case 0:
            return AdvCellID;
            break;
        case 1:
            return NavCellID;
            break;
        default:
            return normalCellID;
            break;
    }
}

@end
